package com.ella.utils;
import com.alibaba.fastjson2.JSONObject;
import com.ella.common.security.exception.TokenException;
import com.ella.common.security.exception.UsernameAndPasswordNotMatch;
import com.ella.entity.security.LoginUser;
import io.jsonwebtoken.*;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
	//有效期为
	public static final Long JWT_TTL = 100L;// 60 * 60 *1000  过期时间为30分钟
	//设置秘钥明文
	public static final String JWT_KEY = "qx";

	public static String getUUID() {
		String token = UUID.randomUUID().toString().replaceAll("-", "");
		return token;
	}

	/**
	 * 生成jtw  jwt加密
	 *
	 * @return
	 */
	public static String createJWT(String subject) {
		JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
		return builder.compact();
	}

	/**
	 * 生成jtw  jwt加密
	 *
	 * @param subject   token中要存放的数据（json格式）
	 * @param ttlMillis token超时时间
	 * @return
	 */
	public static String createJWT(String subject, Long ttlMillis) {
		JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
		return builder.compact();
	}


	/**
	 * 创建token jwt加密
	 *
	 * @param id
	 * @param subject
	 * @param ttlMillis
	 * @return
	 */
	public static String createJWT(String id, String subject, Long ttlMillis) {
		JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
		return builder.compact();
	}

	private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		SecretKey secretKey = generalKey();
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		if (ttlMillis == null) {
			//TODO 如果用户没有设置token的过期时间默认设置为30分钟
			ttlMillis = JwtUtil.JWT_TTL;
		}

		long expMillis = nowMillis + ttlMillis;
		Date expDate = new Date(expMillis);
		return Jwts.builder()
				.setId(uuid)              //唯一的ID
				.setSubject(subject)     // 主题  可以是JSON数据
				.setIssuer("sg")        // 签发者
				.setIssuedAt(now)      // 签发时间
				.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
				.setExpiration(expDate);
	}



	public static void main(String[] args) {
		SecretKey secretKey = generalKey();
		System.out.println(secretKey);
		System.out.println(secretKey.getAlgorithm());
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		System.out.println(signatureAlgorithm.isRsa());

	}

	/**
	 * 生成加密后的秘钥 secretKey
	 * @return
	 */
	public static SecretKey generalKey() {
		byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
		SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
		return key;
	}

	/**
	 * jwt解密
	 *
	 * @param jwt
	 * @return
	 * @throws Exception
	 */
	public static LoginUser parseJWT(String jwt) {
		SecretKey secretKey = generalKey();
		String subject = null;
		Claims body =null;
		try {
			body = Jwts.parser()
					.setSigningKey(secretKey)
					.parseClaimsJws(jwt)
					.getBody();
			 subject = body.getSubject();
		}catch (RuntimeException runtimeException){
			if (runtimeException instanceof ExpiredJwtException) {
				throw new TokenException("token令牌过期了");
			} else {
				throw new TokenException("token非法，请重新登录");
			}
		}
		//解析subject成LoginUser实体类
		return JSONObject.parseObject(subject, LoginUser.class);
	}

	public static void verifyToken(LoginUser loginUser) {
		long expireTime = loginUser.getExpireTime();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= JWT_TTL) {
			refreshToken(loginUser);
		}else {
			throw  new TokenException("令牌过期,请重新登录");
		}
	}

	private static void refreshToken(LoginUser loginUser) {
		loginUser.setLoginTime(System.currentTimeMillis());
		loginUser.setExpireTime(loginUser.getLoginTime() + JWT_TTL);
		// 根据uuid将loginUser缓存
	}
}
